package top.chengdongqing.mishop.auth

import org.springframework.http.HttpStatus
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*
import top.chengdongqing.mishop.common.constants.RegexPatterns
import top.chengdongqing.mishop.utils.VerificationCodeUtils

@RestController
@RequestMapping("/auth")
class AuthController(
    private val authService: AuthService,
    private val verificationCodeUtils: VerificationCodeUtils
) {

    @PostMapping("/login/password")
    fun loginByPassword(@RequestParam account: String, @RequestParam password: String): AuthVO {
        return authService.loginByPassword(account, password)
    }

    @PostMapping("/login/verification-code")
    fun loginByVerificationCode(@RequestParam phoneNumber: String, @RequestParam verificationCode: String): AuthVO {
        return authService.loginByVerificationCode(phoneNumber, verificationCode)
    }

    @PostMapping("/signup")
    @ResponseStatus(HttpStatus.CREATED)
    fun signup(
        @RequestParam phoneNumber: String,
        @RequestParam verificationCode: String,
        @RequestParam password: String
    ): AuthVO {
        return authService.signup(phoneNumber, verificationCode, password)
    }

    @PutMapping("/password/reset")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun resetPassword(
        @RequestParam account: String,
        @RequestParam verificationCode: String,
        @RequestParam newPassword: String
    ) {
        authService.resetPassword(account, verificationCode, newPassword)
    }

    @PreAuthorize("isAuthenticated()")
    @PostMapping("/token/refresh")
    fun refreshToken(@RequestBody token: String): Token {
        return authService.refreshToken(token)
    }

    @GetMapping("/verification-code")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun sendVerificationCode(@RequestParam recipient: String) {
        if (RegexPatterns.PHONE_NUMBER.matches(recipient)) {
            verificationCodeUtils.sendBySms(recipient)
        } else if (RegexPatterns.EMAIL.matches(recipient)) {
            verificationCodeUtils.sendByEmail(recipient)
        } else {
            throw IllegalArgumentException("发送验证码失败：无效账号")
        }
    }
}